<?php namespace App\Http\Controllers\Api;

use App\DakaContent;
use App\DakaUser;
use App\FollowIntegral;
use App\Http\Controllers\Controller;
use App\Http\Services\UserManager;
use App\Message;
use App\SysFeedback;
use App\User;
use App\Userinfo;
use App\UserRanking;
use Illuminate\Http\Request;

class UcenterController extends Controller
{
    public function getUserInfo(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);

        if(!$user)
            return response()->json(['level'=>'error',"message"=>"no_login","data"=>"no_login"]);

        /** @var Userinfo $userInfo */
        $userInfo = Userinfo::whereUserId($user->id)->first();

        if(!$userInfo){
            return response()->json(['level'=>'error',"message"=>"用户资料不存在","data"=>""]);
        }

        $userInfo->photo_url = route("Api.File.showImageById",["id"=>$userInfo->photo_id]);

        return response()->json(["level"=>"success","message"=>"获取用户信息成功","data"=>$userInfo]);
    }

    public function getMyDakaList(Request $request){
        /** @var User $user */
        $user  = UserManager::isLogin($request);
        $limit = !is_null($request->get("limit")) ? $request->get("limit"):10;

        if(!$user)
            return response()->json(['level'=>'error',"message"=>"no_login","data"=>"no_login"]);

        $myDakaList = DakaUser::whereUserId($user->id)->orderBy('created_at','desc')->limit($limit)->get();
        if(count($myDakaList) > 0){
            foreach ($myDakaList as $key=>$myDaka){
                /** @var DakaUser $myDaka */
                /** @var DakaContent $thatDakaContent */
                $thatDakaContent = DakaContent::whereId($myDaka->d_id)->first();
                if($thatDakaContent){
                    $thatDakaContent->img_url = route("Api.File.showImageById",["id"=>$thatDakaContent->img_id]);

                    $myDaka->daka_content = $thatDakaContent;
                }else{
                    unset($myDakaList[$key]);
//                    $myDaka->daka_content = null;
                }
            }
        }

        return response()->json(["level"=>"success","message"=>"获取用户打卡内容成功","data"=>$myDakaList]);
    }

    public function setUserInfo(Request $request){
        /** @var User $user */
        $user        = UserManager::isLogin($request);
        $photoId     = $request->get('photo_id');
        $nickname    = $request->get('nickname');
        $wxNum       = $request->get("wx_num");
        $birthday    = $request->get("birthday");
        $sex         = $request->get('sex');
        $description = $request->get('description');

        if(!$user)
            return response()->json(['level'=>'error',"message"=>"no_login","data"=>"no_login"]);

        /** @var Userinfo $userInfo */
        $userInfo = Userinfo::whereUserId($user->id)->first();
        if(!$userInfo){
            return response()->json(['level'=>'error',"message"=>"用户信息不存在","data"=>"no_login"]);
        }

        if(!is_null($photoId))$userInfo->photo_id = $photoId;
        if(!is_null($nickname))$userInfo->nickname = $nickname;
        if(!is_null($wxNum))$userInfo->wechat = $wxNum;
        if(!is_null($birthday))$userInfo->birthday = $birthday;
        if(!is_null($sex))$userInfo->sex = $sex;
        if(!is_null($description))$userInfo->description = $description;

        $userInfo->save();

        return response()->json(["level"=>"success","message"=>"设置用户信息完成","data"=>$userInfo]);
    }

    public function getRanking(Request $request){
        $user = UserManager::isLogin($request);

        if(!$user)
            return response()->json(['level'=>'error',"message"=>"no_login","data"=>"no_login"]);

        /** @var Userinfo $userInfo */
        $userInfo = Userinfo::whereUserId($user->id)->first();
        if(!$userInfo)
            return response()->json(['level'=>'error',"message"=>"用户信息不存在"]);

        //获取当天的最大时间和最小时间
        $ty = date('Y', time());
        $tm = date('m', time());
        $td = date('d', time());
        $todayStartTime = mktime(0,0,0,$tm,$td,$ty);
        $todayEndTime   = mktime(23,59,59,$tm,$td,$ty);

        $time = time();
        $w_day=date("w",$time);
        if($w_day=='1'){
            $cflag = '+0';
        }else {
            $cflag = '-1';
        }
        //本周一零点的时间戳
        $start_time = strtotime(date('Y-m-d',strtotime("$cflag week Monday", $time)));
        //本周末零点的时间戳
        $stop_time = strtotime(date('Y-m-d',strtotime("$cflag week Monday", $time)))+7*24*3600;

        $allUser = User::all();
        if(count($allUser) > 0){
            foreach ($allUser as $theUser){
                /** @var UserRanking $thatUserRanking */
                $thatUserRanking = UserRanking::whereUserId($theUser->id)->first();
                if(!$thatUserRanking){
                    $thatUserRanking = new UserRanking();
                    $thatUserRanking->user_id = $theUser->id;
                }

                /** @var User $theUser */
                $todayUserIntegralSum = FollowIntegral::whereUserId($theUser->id)->whereBetween("created_at",[date("Y-m-d H:i:s",$todayStartTime),date("Y-m-d H:i:s",$todayEndTime)])->sum("integral");
                $weekUserIntegralSum = FollowIntegral::whereUserId($theUser->id)->whereBetween("created_at",[date("Y-m-d H:i:s",$start_time),date("Y-m-d H:i:s",$stop_time)])->sum("integral");
                $allUserIntegralSum = FollowIntegral::whereUserId($theUser->id)->sum("integral");

                $thatUserRanking->today_sum = !is_null($todayUserIntegralSum) ? $todayUserIntegralSum : 0;
                $thatUserRanking->week_sum  = !is_null($weekUserIntegralSum) ? $weekUserIntegralSum : 0;
                $thatUserRanking->all_sum   = !is_null($allUserIntegralSum) ? $allUserIntegralSum : 0;
                $thatUserRanking->save();
            }
        }

        $todayList = UserRanking::orderBy("today_sum","desc")->limit(20)->get();
        $weekList  = UserRanking::orderBy("week_sum","desc")->limit(20)->get();
        $allList   = UserRanking::orderBy("all_sum","desc")->limit(20)->get();

        if(count($todayList) > 0){
            foreach ($todayList as $todayRank){
                /** @var UserRanking $todayRank */
                /** @var Userinfo $theUserInfo */
                $theUserInfo = Userinfo::whereUserId($todayRank->user_id)->first();
                if($theUserInfo){
                    $resultUserinfo['nickname']  = $theUserInfo->nickname;
                    $resultUserinfo["photo_url"] = route("Api.File.showImageById",["id"=>$theUserInfo->photo_id]);
                }else{
                    $resultUserinfo['nickname']  = '';
                    $resultUserinfo["photo_url"] = '';
                }

                $todayRank->userinfo = $resultUserinfo;
                $todayRank->ranking_num = $todayRank->today_sum;
                unset($todayRank->week_sum);
                unset($todayRank->all_sum);
                unset($todayRank->today_sum);
                unset($todayRank->updated_at);
                unset($todayRank->user_id);
                unset($todayRank->deleted_at);
            }
        }

        if(count($weekList) > 0){
            foreach ($weekList as $weekRank){
                /** @var UserRanking $todayRank */
                /** @var Userinfo $theUserInfo */
                $theUserInfo = Userinfo::whereUserId($weekRank->user_id)->first();
                if($theUserInfo){
                    $resultUserinfo['nickname']  = $theUserInfo->nickname;
                    $resultUserinfo["photo_url"] = route("Api.File.showImageById",["id"=>$theUserInfo->photo_id]);
                }else{
                    $resultUserinfo['nickname']  = '';
                    $resultUserinfo["photo_url"] = '';
                }

                $weekRank->userinfo = $resultUserinfo;
                $weekRank->ranking_num = $weekRank->week_sum;
                unset($weekRank->week_sum);
                unset($weekRank->all_sum);
                unset($weekRank->today_sum);
                unset($weekRank->updated_at);
                unset($weekRank->user_id);
                unset($weekRank->deleted_at);
            }
        }

        $myRanking = 0;
        if(count($allList) > 0){
            $i = 1;
            foreach ($allList as $allRank){
                /** @var UserRanking $allRank */
                /** @var Userinfo $theUserInfo */
                $theUserInfo = Userinfo::whereUserId($allRank->user_id)->first();
                if($theUserInfo){
                    $resultUserinfo['nickname']  = $theUserInfo->nickname;
                    $resultUserinfo["photo_url"] = route("Api.File.showImageById",["id"=>$theUserInfo->photo_id]);
                }else{
                    $resultUserinfo['nickname']  = '';
                    $resultUserinfo["photo_url"] = '';
                }

                if($allRank->user_id == $user->id){
                    $myRanking = $i;
                }

                $i++;
                $allRank->userinfo = $resultUserinfo;
                $allRank->ranking_num = $allRank->all_sum;
                unset($allRank->week_sum);
                unset($allRank->all_sum);
                unset($allRank->today_sum);
                unset($allRank->updated_at);
                unset($allRank->user_id);
                unset($allRank->deleted_at);
            }
        }

        $result["my_rank"] = $myRanking;
        $result["today_list"] = $todayList;
        $result["week_list"] = $weekList;
        $result["all_list"] = $allList;

        return response()->json(["level"=>"success","message"=>"获取列表成功","data"=>$result]);
    }

    public function setFeedback(Request $request){
        $user = UserManager::isLogin($request);

        if(!$user)
            return response()->json(['level'=>'error',"message"=>"no_login","data"=>"no_login"]);

        $title   = $request->get('title');
        $content = $request->get("content");

        $newFeedBack = new SysFeedback();
        $newFeedBack->title   = $title;
        $newFeedBack->content = $content;
        $newFeedBack->save();

        return response()->json(["level"=>"success","message"=>"感谢您的反馈","data"=>$newFeedBack]);
    }

    public function getMessageList(Request $request){
        $user = UserManager::isLogin($request);

        if(!$user)
            return response()->json(['level'=>'error',"message"=>"no_login","data"=>"no_login"]);

        $startTime = time();
        $endTime   = time() - (86400 * 7);

//        $allMessage = Message::whereToUserId($user->id)->whereBetween("created_at",[date("Y-m-d H:i:s",$startTime),date("Y-m-d H:i:s",$endTime)])->get();
        $allMessage = Message::whereToUserId($user->id)->get();

        if(count($allMessage)>0){
            foreach ($allMessage as $message){
                /** @var Message $message */
                $fromUserInfo = Userinfo::whereUserId($message->user_id)->first();
                if($fromUserInfo){
                    $fromUserInfo->photo_url = route("Api.File.showImageById",["id"=>$fromUserInfo->photo_id]);

                    $message->from_userinfo = $fromUserInfo;
                }else{
                    $message->from_userinfo = null;
                }

                $thatDaKa = DakaContent::whereId($message->d_id)->first();
                if($thatDaKa){
                    /** @var DakaContent $thatDaka */
                    $thatDaKa->img_url =  route("Api.File.showImageById",["id"=>$thatDaKa->img_id]);

                    $message->daka_info = $thatDaKa;
                }else{
                    $message->daka_info = null;
                }
            }
        }

        return response()->json(["level"=>"success","message"=>"获取我的消息列表成功","data"=>$allMessage]);
    }
}